package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {


    private final ClazzMapper clazzMapper;
    @Autowired
    private final EmpServiceImpl empServiceImpl;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private StudentServiceImpl studentServiceImpl;

    public ClazzServiceImpl(ClazzMapper clazzMapper, EmpServiceImpl empServiceImpl) {
        this.clazzMapper = clazzMapper;
        this.empServiceImpl = empServiceImpl;
    }

    @Override
    public PageResult<Clazz> getPage(String name, LocalDate begin, LocalDate end, int page, int pageSize) {

        // 分页查询
        Page<Clazz> pages = Page.of(page, pageSize);
        //  按照最后修改时间倒叙排序
        pages.addOrder(OrderItem.desc("update_time"));
        //条件分页查询
        pages = lambdaQuery().like(name != null && !name.isEmpty(), Clazz::getName, name)
                .between(begin != null && end != null,Clazz::getEndDate,  begin, end)
                .page(pages);
        //将班主任Id赋值给班主任姓名
        List<Integer> masterIds = pages.getRecords().stream().map(clazz -> clazz.getMasterId()).collect(Collectors.toList());
        if (masterIds.isEmpty()) {
            return new PageResult<>(pages.getTotal(), pages.getRecords());
        }
        //通过班主任ids批量查询员工
        List<Emp> emps = empServiceImpl.listByIds(masterIds);
        //  将员工信息填充到班主任中
        // 将员工信息转换为Map，便于快速查找
        Map<Integer, String> empMap = emps.stream()
                .collect(Collectors.toMap(Emp::getId, Emp::getName));

        // 填充班主任姓名
        for (Clazz clazz : pages.getRecords()) {
            Integer masterId = clazz.getMasterId();
            if (empMap.containsKey(masterId)) {
                clazz.setMasterName(empMap.get(masterId));
            }
        }
        //填充状态
        for (Clazz clazz : pages.getRecords()) {
            if (clazz.getBeginDate().isAfter(LocalDate.now())) {
                clazz.setStatus("未开课");
            } else if (clazz.getEndDate().isAfter(LocalDate.now())) {
                clazz.setStatus("未结课");
            } else {
                clazz.setStatus("已结课");
            }
        }


        return new PageResult<>(pages.getTotal(), pages.getRecords());
    }
    /**
     * 新增班级信息
     */
    @Override
    public void saveClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        save(clazz);
    }

    /**
     * 获取班级信息
     *
     */
   /* @Override
    public Clazz getClazzById(Integer id) {

        Clazz byId = getById(id);
        if (byId != null) {
            Integer masterId = byId.getMasterId();
            Emp emp = empServiceImpl.getById(masterId);
            byId.setMasterName(emp.getName());
            if (byId.getBeginDate().isAfter(LocalDate.now())) {
                byId.setStatus("未开课");
            } else if (byId.getEndDate().isAfter(LocalDate.now())) {
                byId.setStatus("未结课");
            } else {
               byId.setStatus("已结课");
            }
        }
        return byId;
    }*/

    @Override
    public void updateClazzById(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        updateById(clazz);
    }

    @Override
    public void removeClazzById(Integer id) {
        //根据班级id查询学生信息
        List<Student> students = studentServiceImpl.list(new QueryWrapper<Student>().eq("clazz_id", id));
        if (students.isEmpty()){
            removeById(id);
        }else {
            throw new RuntimeException("该班级下有学生，不能删除");
        }

    }
}
